const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: defaultAvatarUrl,
    nickname: '微信用户',
    gender: '', // 默认为男性
    birthday: ''
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
   
    //从后端数据库获取用户信息
    const openid=wx.getStorageSync('openid');
    const that=this;
    wx.request({
      url: 'http://localhost:3000/user/info',
      method: 'GET',
      data: {
        openid: openid
      },
      success(res) {
        if (res.data.code === 0) {
          const userInfo=res.data.userInfo;
         const birthday= userInfo.birthday.slice(0,10)
          that.setData({
            avatarUrl: userInfo.avatar ,
            nickname: userInfo.nickname ,
            gender: userInfo.gender ,
            birthday: birthday
          })
        } else {
          wx.showToast({
            title: '获取信息失败,未登录，请重新登录',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail() {
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.setData({
      avatarUrl: avatarUrl
    })
  },

  getUserName(e) {
    const openid = wx.getStorageSync('openid')

    // 向后端发送POST请求，更新用户信息
    wx.request({
      url: 'http://localhost:3000/user/update',
      method: 'POST',
      data: {
        openid,
        nickname: e.detail.value.nickname,
        avatarUrl: this.data.avatarUrl,
        gender: this.data.gender,
        birthday: this.data.birthday
      },
      success(res) {
        if (res.data.code === 0) {
          wx.showToast({
            title: '更新成功',
            icon: 'success',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '更新失败',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail() {
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000
        })
      }
    })
   
    wx.navigateBack({     // 将wx.navigateTo替换为wx.navigateBack
      delta: 1
    })
  },

  genderChange(e) {
    // wx.setStorageSync('gender', e.detail.value)
    this.setData({
      gender: e.detail.value
    })
  },

  birthdayChange(e) {
    // wx.setStorageSync('birthday', e.detail.value)
    this.setData({
      birthday: e.detail.value
    })
  },
  clear() {
    wx.clearStorage({
      success: (res) => {
        wx.navigateBack({
          delta: 1,
        })
        
      },
    })
  }
})
